package cn.topcodes.tcsf.app.web.controller.userend;

import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.app.domain.form.AppClientInfo;
import cn.topcodes.tcsf.app.service.AppUserService;
import cn.topcodes.tcsf.app.web.controller.userend.interceptor.IgnoreUserendAuth;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Unicorn on 2018/1/13.
 */
@RestController
@RequestMapping("/userend")
public class UserEndPersonalController {

    @Autowired
    private AppUserService appUserService;

    /**
     * 请求登录
     * @param username  用户名
     * @param password  密码
     * @return
     */
    @IgnoreUserendAuth
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ApiResponseEntity login(
            @RequestParam(required = true) String username,
            @RequestParam(required = true) String password,
            HttpSession session
    ) {
        AppClientInfo appClientInfo = new AppClientInfo();
        appClientInfo.setApp(AppClientInfo.APP_DEFAULT);
        appClientInfo.setPlatform(AppClientInfo.PLATFORM_PC_WEB);
        appClientInfo.setAppVersion(AppClientInfo.APP_VERSION_UNKNOWN);
        appClientInfo.setTerminal(AppClientInfo.TERMINAL_UNKNOWN);
        String token = appUserService.login(username, password, appClientInfo);
        session.setAttribute("token", token);
        return ApiResponseEntity.buildOK();
    }

    @RequestMapping(value = "menu", method = RequestMethod.GET)
    public void menu(HttpServletResponse response) throws IOException {
        InputStream in = this.getClass().getResourceAsStream("/userend-menu.json");
        IOUtils.copy(in, response.getOutputStream(), 1024);
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ApiResponseEntity logout(HttpSession session) {
        String token = (String) session.getAttribute("token");
        appUserService.logout(token);
        return ApiResponseEntity.buildOK();
    }

}
